/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package unipiloto.edu.co.auth.service.impl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import unipiloto.edu.co.auth.service.api.UserAuthenticacionService;
import unipiloto.edu.co.auth.service.entity.User;

/**
 *
 * @author David
 */
@Stateless
public class UserAuthenticacionServiceEJB implements UserAuthenticacionService {

    @PersistenceContext(unitName="autenticacion_usuarios_PU")
    private EntityManager em;
    
    public List<String> listAll() {
        List<String> listaMetodos = new ArrayList<String>();

        Class miClase = UserAuthenticacionService.class;
        Method[] metodos = miClase.getDeclaredMethods();

        for (Method method : metodos) {
            listaMetodos.add(method.getName());
        }

        return listaMetodos;
    }

    public List<String> listRegisteredUsers() {
        List<String> reportsList = new ArrayList<String>();
        for(User user: findRegisteredUsers()){
            reportsList.add(user.getUsername() + "-" + user.getPassword());
        }
        return reportsList;
    }

    public boolean login(String username, String password) {
        if (username == null || password == null) return false;
        User user = em.find(User.class, username);
        return (user!=null && user.passwordValidation(password));
    }

    public boolean register(String username, String password) {
        User user = new User(username, password);
        em.persist(user);
        return true;
    }

    public boolean changePassword(String username, String oldPassword, String newPassword) {
        if (username == null || oldPassword == null || newPassword == null) return false;
        User user = em.find(User.class, username);
        if(user!=null && user.passwordValidation(oldPassword)){
            user.setPassword(newPassword);
            em.merge(user);
            return true;
        }
        return false;
    }

    private List<User> findRegisteredUsers() {
        return (List<User>) em.createNamedQuery("User.findAll").getResultList();
    }
}
